package com.block.common.util;

import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.exception.BizException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by mah on 2015/11/20.
 */
@SuppressWarnings("deprecation")
public class HttpUtil {
//
//	private static Logger logger= LogFactory.getErrorInfoLog();
	private static PoolingHttpClientConnectionManager connMgr;
	private static PoolingHttpClientConnectionManager connSSLMar;
	private static RequestConfig requestConfig;
	private static final int MAX_TIMEOUT = 20000;
	// 发送请求的客户端单例
	private static CloseableHttpClient httpClient;
	static {
		ConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
		LayeredConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
		Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", plainSocketFactory)
				.register("https", sslSocketFactory).build();
		// 设置连接池
		connMgr = new PoolingHttpClientConnectionManager(registry);
		// 设置连接池大小
		connMgr.setMaxTotal(200);
		connMgr.setDefaultMaxPerRoute(50);

		RequestConfig.Builder configBuilder = RequestConfig.custom();
		// 设置连接超时
		configBuilder.setConnectTimeout(MAX_TIMEOUT);
		// 设置读取超时
		configBuilder.setSocketTimeout(MAX_TIMEOUT);

		// 设置从连接池获取连接实例的超时
		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
		// 在提交请求之前 测试连接是否可用
		configBuilder.setStaleConnectionCheckEnabled(true);
		requestConfig = configBuilder.build();
	}

	public static PoolingHttpClientConnectionManager getConnMgr (){
		return connMgr;
	}

	public static CloseableHttpClient createHttpClient(){
		if(httpClient==null) {
			HttpRequestRetryHandler httpRequestRetryHandler= (exception, executionCount, context) -> false;
			httpClient = HttpClients.custom().setConnectionManager(connMgr).setRetryHandler(httpRequestRetryHandler).setDefaultRequestConfig(requestConfig).build();

		}
		return httpClient;
	}

	/**
	 * 根据类型选择发送方式
	 *
	 * 
	 * @Date 3:29 下午 2020/10/15
	 * @param type
	 * @param keyStorePath
	 * @param password
	 * @return
	 **/
	public static CloseableHttpClient createHttpClientBySSLCert(String type,String keyStorePath, String password){
		switch (type) {
            case "JKS":
                return createHttpClientBySSLCertJks(keyStorePath,password);
            case "PKCS12":
				return createHttpClientBySSLCertPKCS12(keyStorePath,password);
        }
        return null;
	}
	/**
	 * httpclient证书发送方式
	 * @param keyStorePath
	 * @param password
	 * @return
	 */
	public static CloseableHttpClient createHttpClientBySSLCertJks(String keyStorePath, String password){

		CloseableHttpClient closeableHttpClient= null;

		KeyManagerFactory keyFactory = null;
//
//		KeyStore tsstore;
		try {
//			keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//			KeyStore keystore = KeyStore.getInstance("JKS");
//			keystore.load(new FileInputStream(new File(keyStorePath)), null);
//			keyFactory.init(keystore, password.toCharArray());
//			KeyManager[] keyManagers = keyFactory.getKeyManagers();
//			TrustManagerFactory trustFactory = null;
//			trustFactory = TrustManagerFactory.getInstance("SunX509");
//			tsstore = KeyStore.getInstance("JKS");
//			tsstore.load(new FileInputStream(new File(keyStorePath)), password.toCharArray());
//			trustFactory.init(tsstore);
//			TrustManager[] trustManagers = trustFactory.getTrustManagers();

			System.setProperty("jsse.enableSNIExtension", "false");
			//demo
			KeyStore ks = KeyStore.getInstance("JKS");
			File certFile = new File(keyStorePath);
			ks.load(new FileInputStream(certFile), password.toCharArray());

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			//初始化证书
			kmf.init(ks, password.toCharArray());
			TrustManager[] tm = { new MyX509TrustManager() };

			SSLContext	sslContext = SSLContext.getInstance("TLSv1.2");
			sslContext.init(kmf.getKeyManagers(), tm, null);
			SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext);

			Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
			socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
					.register("http", PlainConnectionSocketFactory.INSTANCE)
					.register("https", ssf).build();
			//池化管理
			connSSLMar = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
			//创建httpClient

			closeableHttpClient = HttpClients.custom().setConnectionManager(connSSLMar).build();
//			log.info("tsstore ="+tsstore+"
		} catch (Exception e) {
			e.printStackTrace();
//			logger.info("初始化ssl证书发送http通信异常,",e);
		}
		return closeableHttpClient;
	}

	/**
	 * httpclient证书发送方式
	 * @param keyStorePath
	 * @param password
	 * @return
	 */
	public static CloseableHttpClient createHttpClientBySSLCertPKCS12(String keyStorePath, String password){

		CloseableHttpClient closeableHttpClient= null;

		KeyManagerFactory keyFactory = null;
		try {

			System.setProperty("jsse.enableSNIExtension", "false");
			//demo
			KeyStore ks = KeyStore.getInstance("PKCS12");
			File certFile = new File(keyStorePath);
			ks.load(new FileInputStream(certFile), password.toCharArray());

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			//初始化证书
			kmf.init(ks, password.toCharArray());
			TrustManager[] tm = { new MyX509TrustManager() };

			SSLContext	sslContext = SSLContext.getInstance("TLSv1.2");
			sslContext.init(kmf.getKeyManagers(), tm, null);
			SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext);

			Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
			socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
					.register("http", PlainConnectionSocketFactory.INSTANCE)
					.register("https", ssf).build();
			//池化管理
			connSSLMar = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
			//创建httpClient

			closeableHttpClient = HttpClients.custom().setConnectionManager(connSSLMar).build();
//			log.info("tsstore ="+tsstore+"
		} catch (Exception e) {
			e.printStackTrace();
//			logger.info("初始化ssl证书发送http通信异常,",e);
		}
		return closeableHttpClient;
	}

	public static CloseableHttpClient createHttpClient(String url){
		if(httpClient==null) {
			HttpHost httpHost = new HttpHost(url);
			connMgr.setMaxPerRoute(new HttpRoute(httpHost), 50);
			HttpRequestRetryHandler httpRequestRetryHandler= (exception, executionCount, context) -> false;
			httpClient = HttpClients.custom().setConnectionManager(connMgr).setRetryHandler(httpRequestRetryHandler).setDefaultRequestConfig(requestConfig).build();
		}
		return httpClient;
	}

	/**
	 * 发送 GET 请求（HTTP），不带输入数据
	 *
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		return doGet(url, new HashMap<String, Object>(10));
	}

	public static String doPost2(String apiUrl, Map<String, Object> params,Map<String, String> headers) {
		CloseableHttpClient httpClient = createHttpClient();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			if(headers!=null&&headers.size()>0)
			{
				for(String key:headers.keySet())
				{
					httpPost.setHeader(key,headers.get(key));
				}
			}
			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}


	/**
	 * 发送 GET 请求（HTTP），K-V形式
	 *
	 * @param url
	 * @param params
	 * @return
	 */
	@SuppressWarnings("resource")
	public static String doGet(String url, Map<String, Object> params) {
		String apiUrl = url;
		StringBuffer param = new StringBuffer();
		int i = 0;
		for (String key : params.keySet()) {
			if (i == 0) {
				param.append("?");
			} else {
				param.append("&");
			}
			param.append(key).append("=").append(params.get(key));
			i++;
		}
		apiUrl += param;
		String result = null;
		HttpClient httpclient =createHttpClient();
		HttpResponse response=null;
		HttpGet httpPost=null;
		try {
			httpPost= new HttpGet(apiUrl);
			response= httpclient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();


			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				result = IOUtils.toString(instream, "UTF-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(httpPost!=null)
			{
				httpPost.releaseConnection();
			}
		}
		return result;
	}

	/**
	 * 发送 POST 请求（HTTP），不带输入数据
	 *
	 * @param apiUrl
	 * @return
	 */
	public static String doPost(String apiUrl) {
		return doPost(apiUrl, new HashMap<String, Object>(10));
	}

	/**
	 * 发送 POST 请求（HTTP），K-V形式
	 *
	 * @param apiUrl
	 *            API接口URL
	 * @param params
	 *            参数map
	 * @return
	 */
	public static String doPostMap(String apiUrl, Map<String, Object> params) {
		CloseableHttpClient httpClient = createHttpClient();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			httpPost.setConfig(requestConfig);
			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 POST 请求（HTTP），JSON形式
	 *
	 * @param apiUrl
	 * @param json
	 *            json对象
	 * @return
	 */
	public static String doPost(String apiUrl, Object json) {
		CloseableHttpClient httpClient = createHttpClient();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			// System.out.println(response.getStatusLine().getStatusCode());
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 POST 请求（HTTP），JSON形式
	 *
	 * @param apiUrl
	 * @param json
	 *            json对象
	 * @return
	 */
	public static String doPost(String apiUrl, Object json, Map<String, String> headerMap) {
		CloseableHttpClient httpClient = createHttpClient();
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			if(headerMap!=null){
				for(String key:headerMap.keySet()){
					httpPost.setHeader(key,headerMap.get(key));
				}
			}
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			// System.out.println(response.getStatusLine().getStatusCode());
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送带证书的https通信
	 * @param apiUrl
	 * @param json
	 * @param keyStrorePath
	 * @param password
	 * @return
	 */
	public static String doPostBySSLCert(String type,String apiUrl, Object json,String keyStrorePath,String password,Map<String,String> headers) {
		CloseableHttpClient httpClient =createHttpClientBySSLCert(type,keyStrorePath,password);
		String httpStr = null;
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;

		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");

			if(headers!=null)
			{
				for(String key:headers.keySet())
				{
					httpPost.setHeader(key,headers.get(key));
				}
			}

			httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			// System.out.println(response.getStatusLine().getStatusCode());
			httpStr = EntityUtils.toString(entity, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
//			httpClient.getConnectionManager().closeExpiredConnections();
			connSSLMar.closeExpiredConnections();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 SSL POST 请求（HTTPS），K-V形式
	 *
	 * @param apiUrl
	 *            API接口URL
	 * @param json
	 * @return InputStream
	 */
	public static File doPostSSL(String apiUrl,JSONObject json) throws IOException, BizException {
		CloseableHttpClient httpClient = createHttpClient();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		InputStream inputStream=null;
		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toJSONString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			Header[] contentTypeHeader = response.getHeaders("Content-Type");
			if (contentTypeHeader != null && contentTypeHeader.length > 0) {
				if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) {
					// application/json; encoding=utf-8 下载媒体文件出错
					throw new BizException(AppRspCodeConstant.THRID_FAILED,EntityUtils.toString(entity, "UTF-8"));
				}
			}
			inputStream=entity.getContent();
			File file= File.createTempFile("abc/bbc/",".png");
			FileUtils.copyInputStreamToFile(inputStream,file);
			return file;
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(inputStream!=null){
				inputStream.close();
			}
		}
	}
	/**
	 * 发送 SSL POST 请求（HTTPS），K-V形式
	 *
	 * @param apiUrl
	 *            API接口URL
	 * @param params
	 *            参数map
	 * @return
	 */
	public static String doPostSSL(String apiUrl, Map<String, Object> params,Map<String, String> headers) {
		CloseableHttpClient httpClient = createHttpClient();
//		HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
//				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			if(headers!=null&&headers.size()>0)
			{
				for(String key:headers.keySet())
				{
					httpPost.setHeader(key,headers.get(key));
				}
			}
			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				System.out.println(statusCode);
				System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 SSL POST 请求（HTTPS），K-V形式
	 *
	 * @param apiUrl
	 *            API接口URL
	 * @param params
	 *            参数map
	 * @return
	 */
	public static String doPostSSL(String apiUrl, Map<String, Object> params, String head) {
		CloseableHttpClient httpClient = createHttpClient();
//				HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
//				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = new HttpPost(apiUrl);
		httpPost.setHeader("Content-type", head);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
				pairList.add(pair);
			}
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
//					log.error("【释放链接异常】异常信息：" + e.getMessage());
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 *
	 * @param apiUrl
	 * @param json
	 * @return
	 */
	public  static  String doPostByScheme(String apiUrl, Object json)throws Exception
	{
		if(apiUrl.startsWith("https"))
		{
			return doPostSSL(apiUrl,json);
		}else
		{
			return doPost(apiUrl,json);
		}
	}

	public  static  String doPostMapScheme(String apiUrl, Map<String,Object> map)
	{
		if(apiUrl.startsWith("https"))
		{
			return doPostSSL(apiUrl,map,new HashMap<>(0));
		}else
		{
			return doPost2(apiUrl,map,null);
		}
	}
	public  static  String doPostMapScheme(String apiUrl, Map<String,Object> map,Map<String,String> head)
	{
		if(apiUrl.startsWith("https"))
		{
			return doPostSSL(apiUrl,map,head);
		}else
		{
			return doPost2(apiUrl,map,head);
		}
	}
	/**
	 * 发送 SSL POST 请求（HTTPS），JSON形式
	 *
	 * @param apiUrl
	 *            API接口URL
	 * @param json
	 *            JSON对象
	 * @return
	 */
	public static String doPostSSL(String apiUrl, Object json) throws IOException {
		CloseableHttpClient httpClient = createHttpClient();

//				HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
//				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
		HttpPost httpPost = new HttpPost(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpPost.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json;charset=UTF-8");
			httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			System.out.println("statusCode:"+statusCode);
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");

		} catch (Exception e) {
			e.printStackTrace();
			throw  e;
		} finally {
			httpPost.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 发送 SSL POST 请求（HTTPS），JSON形式
	 *
	 * @param apiUrl
	 *            API接口URL
	 * @param json
	 *            JSON对象
	 * @return
	 */
	public static String doGetSSL(String apiUrl, Object json) {
		CloseableHttpClient httpClient = createHttpClient();

//				HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
//				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();

		HttpGet httpGet = new HttpGet(apiUrl);
		CloseableHttpResponse response = null;
		String httpStr = null;

		try {
			httpGet.setConfig(requestConfig);
			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");

			response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				return null;
			}
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				return null;
			}
			httpStr = EntityUtils.toString(entity, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpGet.releaseConnection();
			if (response != null) {
				try {
					EntityUtils.consume(response.getEntity());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return httpStr;
	}

	/**
	 * 创建SSL安全连接
	 *
	 * @return
	 */
//	private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
//		SSLConnectionSocketFactory sslsf = null;
//		try {
//			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
//
//				@Override
//				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//					return true;
//				}
//			}).build();
//			sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
//
//				@Override
//				public boolean verify(String arg0, SSLSession arg1) {
//					return true;
//				}
//
//				@Override
//				public void verify(String host, SSLSocket ssl) throws IOException {
//				}
//
//				@Override
//				public void verify(String host, X509Certificate cert) throws SSLException {
//				}
//
//				@Override
//				public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
//				}
//			});
//		} catch (GeneralSecurityException e) {
//			e.printStackTrace();
//		}
//		return sslsf;
//	}
	static class MyX509TrustManager implements X509TrustManager {



		public MyX509TrustManager() throws Exception {

		}

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {

		}
		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {

		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		}
	}

	/**
	 * form表单上传文件和表单数据
	 * @param url
	 * @param fileMap
	 * @param params
	 * @param header
	 * @return
	 */
	public static String doUploadFileAndParams(String url, Map<String,File> fileMap,Map<String,Object> params,Map<String,Object> header){
		String ret ="";
		HttpPost post = new HttpPost(url);
		CloseableHttpClient httpClient = createHttpClient();
		CloseableHttpResponse response = null;
		try {
			MultipartEntityBuilder entityBuilder =  MultipartEntityBuilder.create();
			ContentType contentType=ContentType.create("multipart/form-data","UTF-8");
			entityBuilder.setContentType(contentType);
			if(fileMap!=null&&fileMap.size()>0){
				for(Map.Entry<String,File> fileEntry:fileMap.entrySet()){
					entityBuilder.addBinaryBody(fileEntry.getKey(),fileEntry.getValue(),ContentType.DEFAULT_BINARY,fileEntry.getKey());
				}
			}

			if(params!=null){
				for(Map.Entry<String,Object> entry:params.entrySet()){
					entityBuilder.addTextBody(entry.getKey(),entry.getValue().toString());
				}
			}
			post.setEntity(entityBuilder.build());
			if(header!=null){
				for(Map.Entry<String,Object> entry:header.entrySet()){
					post.addHeader(entry.getKey(),entry.getValue().toString());
				}
			}

			response = httpClient.execute(post);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				ret = EntityUtils.toString(response.getEntity(),"utf-8");
			}else{
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(response!=null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return  ret;
	}
	/**
	 * form表单上传文件和表单数据
	 * @param url
	 * @param fileMap
	 * @param params
	 * @param header
	 * @return
	 */
	public static String doUploadInputStreamAndParams(String url, Map<String,InputStream> fileMap,Map<String,Object> params,Map<String,Object> header){
		String ret ="";
		HttpPost post = new HttpPost(url);
		CloseableHttpClient httpClient = createHttpClient();
		CloseableHttpResponse response = null;
		try {
			MultipartEntityBuilder entityBuilder =  MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
			ContentType contentType=ContentType.create("multipart/form-data");
			entityBuilder.setContentType(contentType);
			if(fileMap!=null&&fileMap.size()>0){
				for(Map.Entry<String,InputStream> fileEntry:fileMap.entrySet()){
					String key=fileEntry.getKey();
					entityBuilder.addBinaryBody(key,fileEntry.getValue(),contentType, key);
				}
			}

			if(params!=null){
				for(Map.Entry<String,Object> entry:params.entrySet()){
					entityBuilder.addTextBody(entry.getKey(),entry.getValue().toString(),contentType);
				}
			}
			post.setEntity(entityBuilder.build());
			if(header!=null){
				for(Map.Entry<String,Object> entry:header.entrySet()){
					post.addHeader(entry.getKey(),entry.getValue().toString());
				}
			}

			response = httpClient.execute(post);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				ret = EntityUtils.toString(response.getEntity(),"utf-8");
			}else{
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(response!=null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return  ret;
	}

	public static void main(String[] args) {

//		JSONObject jsonObject=JSONObject.parseObject("{\"productId\":\"2\",\"method\":\"\",\"signType\":\"1\",\"aesKey\":\"KcGPMn5I4vogX+KiP/kwVRels3cdO2jvih5rgDKGf+Eusxg0dk/eXccy+8bUBnCXEmYjHRUd2nwtRwDH4czyYA==\",\"bizEnc\":\"1\",\"sign\":\"ktbNc7jiMJJy65veq81ubOpbz/1SFU/mdz5n32Qazp2xslIdoXGcIMW6lpTzLwXJfU95kMSZVVMDY61z7QrUzw==\",\"bizParams\":\"E7TJvW7sQdCi1p4MMdeiU5bEQr/hmqYKiWvYw7PIdYGRyRZUX87V5ZbS4QIW+Vnbsbhp8d7v5zTqxZCJuO9vKz7WknHsphPwWQycR3CIXsX0a+bDJnUN9rYEskTBPP/9HVZTNu7vTB00Mk3diW7l6A==\",\"timestamp\":\"1564478353050\"}");
		JSONObject jsonObject= JSONObject.parseObject("{\"method\":\"BEICHEN_SCORE_QUERY\",\"productId\":\"1\",\"sign\":\"GD6v9qTaJC5q56YybwrZj+voqGHHQkkzf6qLtdAGvyKjtYRZcM7OjvVLsnFFyBClhNCCrgHKdWkNh6RkeWz+z8oj1diF8CiwSjb1T9GepY9uZ//OBMrp9G1GOs0yP/z7pb3iBl9iyqKYztpPDLXkuxtKJ7d4Lmku9czT07LwHlQ=\",\"signType\":\"1\",\"aesKey\":\"KK//5Jb5EnrOEdege8vvRuXrRUw/rV3r7Pq0NMX6EdTdHFKpmOumbBauBt2BmJSVOYV8J3PC3rNW1fbKEq+IhVAGw6Qx/geLXiYe27cqXLr4CYHHhYK70MZ+jPGc9opAxrHaOiegHsSG3uT8/oyuXlmqBtfVxWLQ3mvJTlYJZUI=\",\"bizEnc\":\"1\",\"bizParams\":\"ibqUdiNwythbOHmyVlKRJFI8jsL+pyU50UVFOML/t9U472qmtrmpFTZzxvptSYbPaqfk7HcoYBaa4c5zu2X9s3/H8jAscV4H0p7qHJeOaPB4TmzbN1jc77kmO3jqNfrAS9OWawheQQ5UBzP5X7Yjow==\",\"timestamp\":\"1564561909094\"}");
		String response = null;
		try {
			response = HttpUtil.doPostByScheme("https://uat.crepolaris.com/beichen/1/1/score",jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("xx:"+response);//https://uat.crepolaris.com/beichen/1/1/score
	}
}
